package com.david.mydemo.framework.exception;

import com.david.mydemo.util.MyResponse;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.HttpRequestMethodNotSupportedException;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;

@ControllerAdvice
@Slf4j
public class MyExceptionHandler {

	/**
     * 处理空指针的异常
     */
    @ExceptionHandler(value = NullPointerException.class)
    @ResponseBody
    public MyResponse exceptionHandler(HttpServletRequest req, NullPointerException e) {
        log.error("发生空指针异常！异常信息：" + e.getMessage(), e);
        return new MyResponse().fail("发生空指针异常！");
    }

    /**
     * 处理运行时异常
     */
    @ExceptionHandler(value = RuntimeException.class)
    @ResponseBody
    public MyResponse exceptionHandler(HttpServletRequest req, RuntimeException e) {
        log.error("发生运行时异常！异常信息：" + e.getMessage(), e);
        return new MyResponse().fail("发生运行时异常！");
    }

    /**
     * 请求方式不支持
     */
    @ExceptionHandler(value = HttpRequestMethodNotSupportedException.class)
    @ResponseBody
    public MyResponse handleException(HttpRequestMethodNotSupportedException e) {
        log.error("请求方式不支持，异常信息：" + e.getMessage(), e);
        return new MyResponse().fail("请求方式不支持。");
    }

    /**
     * 处理其他异常
     */
    @ExceptionHandler(value = Exception.class)
    @ResponseBody
    public MyResponse exceptionHandler(HttpServletRequest req, Exception e) {
        log.error("服务器错误！异常信息：" + e.getMessage(), e);
        return new MyResponse().fail("服务器错误！");
    }

}

